<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-steps :active="currentTab" align-center finish-status="success">
          <el-step title="商上链品"/>
        </el-steps>
      </div>
      <el-form ref="formValidate" v-loading="fullscreenLoading" class="formValidate mt20" :rules="ruleValidate"
               :model="formValidate" label-width="120px" @submit.native.prevent>
        <el-row v-show="currentTab === 0" :gutter="24">
          <!-- 商品信息-->
          <el-col v-bind="grid2">
            <el-form-item label="商品名称：" prop="storeName">
              <el-input v-model="formValidate.storeName" maxlength="249" disabled placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商品分类：" prop="cateIds">
              <el-cascader v-model="formValidate.cateIds" :options="merCateList" disabled :props="props2" clearable
                           class="selWidth" :show-all-levels="false"/>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商品关键字：">
              <el-input v-model="formValidate.keyword" placeholder="请输入商品关键字" disabled/>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商品封面图：" prop="image">
              <div class="upLoadPicBox">
                <div v-if="formValidate.image" class="pictrue"><img :src="formValidate.image"></div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont"/>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="上链HASH：" prop="hash">
              <el-input v-model="formValidate.hash" placeholder="请输入链上工艺第一个HASH"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button v-show="currentTab===3 || $route.params.id" type="primary" class="submission"
                     @click="handleSubmit('formValidate')">提交上链
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <CreatTemplates ref="addTemplates" @getList="getShippingList"/>
  </div>
</template>

<script>
import {templateListApi, productCreateApi, categoryApi, productDetailApi, productUpdateApi,productRegiserApi} from '@/api/store'
import {shippingTemplatesList} from '@/api/logistics'
import {clearTreeData} from '@/utils/ZBKJIutil'
import CreatTemplates from '@/views/systemSetting/logistics/shippingTemplates/creatTemplates'
import Templates from "../../appSetting/wxAccount/wxTemplate/index";

const defaultObj = {
  image: '',
  sliderImages: [],
  sliderImage: '',
  storeName: '',
  storeInfo: '',
  keyword: '',
  cateIds: [], // 商品分类id
  cateId: null, // 商品分类id传值
  unitName: '',
  sort: 0,
  giveIntegral: 0,
  ficti: 0,
  isShow: false,
  isBenefit: false,
  isNew: false,
  isGood: false,
  isHot: false,
  isBest: false,
  tempId: '',
  attrValue: [{
    image: '',
    price: 0,
    cost: 0,
    otPrice: 0,
    stock: 0,
    barCode: '',
    weight: 0,
    volume: 0
  }],
  attr: [],
  selectRule: '',
  isSub: false,
  content: '',
  specType: false,
  id: 0,
  couponIds: [],
  coupons: [],
  activity: ['默认', '秒杀', '砍价', '拼团']
}
const objTitle = {
  price: {
    title: '售价'
  },
  cost: {
    title: '成本价'
  },
  otPrice: {
    title: '原价'
  },
  stock: {
    title: '库存'
  },
  barCode: {
    title: '商品编号'
  },
  weight: {
    title: '重量（KG）'
  },
  volume: {
    title: '体积(m³)'
  }
}
const proOptions = [{name: '是否热卖', value: 'isHot'}, {name: '优品推荐', value: 'isGood'}, {
  name: '促销单品',
  value: 'isBenefit'
}, {name: '是否精品', value: 'isBest'}, {name: '是否新品', value: 'isNew'}]
export default {
  name: 'ProductProductAdd',
  components: {Templates, CreatTemplates},
  data() {
    return {
      activity: {'默认': 'red', '秒杀': 'blue', '砍价': 'green', '拼团': 'yellow'},
      props2: {
        children: 'child',
        label: 'name',
        value: 'id',
        multiple: true,
        emitPath: false
      },
      checkboxGroup: [],
      recommend: proOptions,
      tabs: [],
      fullscreenLoading: false,
      props: {multiple: true},
      active: 0,
      OneattrValue: [Object.assign({}, defaultObj.attrValue[0])], // 单规格
      ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])], // 多规格
      ruleList: [],
      merCateList: [], // 商户分类筛选
      shippingList: [], // 运费模板
      formThead: Object.assign({}, objTitle),
      formValidate: Object.assign({}, defaultObj),
      formDynamics: {
        ruleName: '',
        ruleValue: []
      },
      tempData: {
        page: 1,
        limit: 9999
      },
      manyTabTit: {},
      manyTabDate: {},
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      isBtn: false,
      manyFormValidate: [],
      currentTab: 0,
      isChoice: '',
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      },
      ruleValidate: {
        hash: [
          {required: true, message: '请输入链上工艺HASH', trigger: 'blur'}
        ],
        cateIds: [
          {required: true, message: '请选择商品分类', trigger: 'change', type: 'array', min: '1'}
        ],
        keyword: [
          {required: true, message: '请输入商品关键字', trigger: 'blur'}
        ],
        storeInfo: [
          {required: true, message: '请输入商品简介', trigger: 'blur'}
        ],
        image: [
          {required: true, message: '请上传商品图', trigger: 'change'}
        ]
      },
      attrInfo: {},
      tableFrom: {
        page: 1,
        limit: 9999,
        keywords: ''
      },
      tempRoute: {},
      keyNum: 0,
      isAttr: false
    }
  },
  computed: {
    attrValue() {
      const obj = Object.assign({}, defaultObj.attrValue[0])
      delete obj.image
      return obj
    },
    oneFormBatch() {
      const obj = [Object.assign({}, defaultObj.attrValue[0])]
      delete obj[0].barCode
      return obj
    }
  },
  watch: {
    'formValidate.attr': {
      handler: function (val) {
        if (this.formValidate.specType && this.isAttr) this.watCh(val)
      },
      immediate: false,
      deep: true
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
    if (this.$route.params.id && this.formValidate.specType) {
      this.$watch('formValidate.attr', this.watCh)
    }
  },
  mounted() {
    this.formValidate.sliderImages = []
    if (this.$route.params.id) {
      this.setTagsViewTitle()
      this.getInfo()
    }
    // if( this.formValidate.attr.length ){
    //   this.formValidate.attr.map(item => {
    //     this.$set(item, 'inputVisible', false)
    //   })
    // }
    this.getCategorySelect()
    this.getShippingList()
  },
  methods: {
    handleCloseCoupon(tag) {
      this.isAttr = true
      this.formValidate.coupons.splice(this.formValidate.coupons.indexOf(tag), 1)
    },
    addCoupon() {
      const _this = this
      this.$modalCoupon('wu', this.keyNum += 1, this.formValidate.coupons, function (row) {
        _this.formValidate.couponIds = []
        _this.formValidate.coupons = row
        row.map((item) => {
          _this.formValidate.couponIds.push(item.id)
        })
      }, '')
    },
    setTagsViewTitle() {
      const title = '编辑商品'
      const route = Object.assign({}, this.tempRoute, {title: `${title}-${this.$route.params.id}`})
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    onChangeGroup() {
      this.checkboxGroup.includes('isGood') ? this.formValidate.isGood = true : this.formValidate.isGood = false
      this.checkboxGroup.includes('isBenefit') ? this.formValidate.isBenefit = true : this.formValidate.isBenefit = false
      this.checkboxGroup.includes('isBest') ? this.formValidate.isBest = true : this.formValidate.isBest = false
      this.checkboxGroup.includes('isNew') ? this.formValidate.isNew = true : this.formValidate.isNew = false
      this.checkboxGroup.includes('isHot') ? this.formValidate.isHot = true : this.formValidate.isHot = false
    },
    watCh(val) {
      const tmp = {}
      const tmpTab = {}
      this.formValidate.attr.forEach((o, i) => {
        tmp['value' + i] = {title: o.attrName}
        tmpTab['value' + i] = ''
      })
      this.ManyAttrValue = this.attrFormat(val)
      this.ManyAttrValue.forEach((val, index) => {
        const key = Object.values(val.attrValue).sort().join('/')
        if (this.attrInfo[key]) this.ManyAttrValue[index] = this.attrInfo[key]
      })
      this.attrInfo = {}
      this.ManyAttrValue.forEach((val) => {
        this.attrInfo[Object.values(val.attrValue).sort().join('/')] = val
      })
      this.manyTabTit = tmp
      this.manyTabDate = tmpTab
      this.formThead = Object.assign({}, this.formThead, tmp)
    },
    attrFormat(arr) {
      let data = []
      const res = []
      return format(arr)

      function format(arr) {
        if (arr.length > 1) {
          arr.forEach((v, i) => {
            if (i === 0) data = arr[i]['attrValue']
            const tmp = []
            data.forEach(function (vv) {
              arr[i + 1] && arr[i + 1]['attrValue'] && arr[i + 1]['attrValue'].forEach(g => {
                const rep2 = (i !== 0 ? '' : arr[i]['attrName'] + '_') + vv + '$&' + arr[i + 1]['attrName'] + '_' + g
                tmp.push(rep2)
                if (i === (arr.length - 2)) {
                  const rep4 = {
                    image: '',
                    price: 0,
                    cost: 0,
                    otPrice: 0,
                    stock: 0,
                    barCode: '',
                    weight: 0,
                    volume: 0,
                    brokerage: 0,
                    brokerage_two: 0
                  }
                  rep2.split('$&').forEach((h, k) => {
                    const rep3 = h.split('_')
                    if (!rep4['attrValue']) rep4['attrValue'] = {}
                    rep4['attrValue'][rep3[0]] = rep3.length > 1 ? rep3[1] : ''
                  })
                  Object.values(rep4.attrValue).forEach((v, i) => {
                    rep4['value' + i] = v
                  })
                  res.push(rep4)
                }
              })
            })
            data = tmp.length ? tmp : []
          })
        } else {
          const dataArr = []
          arr.forEach((v, k) => {
            v['attrValue'].forEach((vv, kk) => {
              dataArr[kk] = v['attrName'] + '_' + vv
              res[kk] = {
                image: '',
                price: 0,
                cost: 0,
                otPrice: 0,
                stock: 0,
                barCode: '',
                weight: 0,
                volume: 0,
                brokerage: 0,
                brokerage_two: 0,
                attrValue: {[v['attrName']]: vv}
              }
              Object.values(res[kk].attrValue).forEach((v, i) => {
                res[kk]['value' + i] = v
              })
            })
          })
          data.push(dataArr.join('$&'))
        }
        return res
      }
    },
    // 运费模板
    addTem() {
      this.$refs.addTemplates.dialogVisible = true
      this.$refs.addTemplates.getCityList()
    },
    // 添加规则；
    addRule() {
      const _this = this
      this.$modalAttr(this.formDynamics, function () {
        _this.productGetRule()
      })
    },
    // 选择规格
    onChangeSpec(num) {
      this.isAttr = true;
      if (num) this.productGetRule()
    },
    // 选择属性确认
    confirm() {
      this.isAttr = true
      if (!this.formValidate.selectRule) {
        return this.$message.warning('请选择属性')
      }
      const data = []
      this.ruleList.forEach(item => {
        if (item.id === this.formValidate.selectRule) {
          item.ruleValue.forEach(i => {
            data.push({
              attrName: i.value,
              attrValue: i.detail
            })
          })
        }
        this.formValidate.attr = data
      })
    },
    // 商品分类；
    getCategorySelect() {
      categoryApi({status: -1, type: 1}).then(res => {
        this.merCateList = this.filerMerCateList(res)
      })
    },
    filerMerCateList(treeData) {
      return treeData.map((item) => {
        if (!item.child) {
          item.disabled = true
        }
        item.label = item.name
        return item
      })
    },
    // 获取商品属性模板；
    productGetRule() {
      templateListApi(this.tableFrom).then(res => {
        const list = res.list
        for (var i = 0; i < list.length; i++) {
          list[i].ruleValue = JSON.parse(list[i].ruleValue)
        }
        this.ruleList = list
      })
    },
    // 运费模板；
    getShippingList() {
      shippingTemplatesList(this.tempData).then(res => {
        this.shippingList = res.list
      })
    },
    showInput(item) {
      this.$set(item, 'inputVisible', true)
    },
    onChangetype(item) {
      if (item === 1) {
        this.OneattrValue.map(item => {
          this.$set(item, 'brokerage', null)
          this.$set(item, 'brokerageTwo', null)
        })
        this.ManyAttrValue.map(item => {
          this.$set(item, 'brokerage', null)
          this.$set(item, 'brokerageTwo', null)
        })
      } else {
        this.OneattrValue.map(item => {
          delete item.brokerage
          delete item.brokerageTwo
          this.$set(item, 'brokerage', null)
          this.$set(item, 'brokerageTwo', null)
        })
        this.ManyAttrValue.map(item => {
          delete item.brokerage
          delete item.brokerageTwo
        })
      }
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.ManyAttrValue.splice(index, 1)
    },
    // 批量添加
    batchAdd() {
      // if (!this.oneFormBatch[0].pic || !this.oneFormBatch[0].price || !this.oneFormBatch[0].cost || !this.oneFormBatch[0].ot_price ||
      //     !this.oneFormBatch[0].stock || !this.oneFormBatch[0].bar_code) return this.$Message.warning('请填写完整的批量设置内容！');
      for (const val of this.ManyAttrValue) {
        this.$set(val, 'image', this.oneFormBatch[0].image)
        this.$set(val, 'price', this.oneFormBatch[0].price)
        this.$set(val, 'cost', this.oneFormBatch[0].cost)
        this.$set(val, 'otPrice', this.oneFormBatch[0].otPrice)
        this.$set(val, 'stock', this.oneFormBatch[0].stock)
        this.$set(val, 'barCode', this.oneFormBatch[0].barCode)
        this.$set(val, 'weight', this.oneFormBatch[0].weight)
        this.$set(val, 'volume', this.oneFormBatch[0].volume)
        this.$set(val, 'brokerage', this.oneFormBatch[0].brokerage)
        this.$set(val, 'brokerageTwo', this.oneFormBatch[0].brokerageTwo)
      }
    },
    // 添加按钮
    addBtn() {
      this.clearAttr()
      this.isBtn = true
    },
    // 取消
    offAttrName() {
      this.isBtn = false
    },
    clearAttr() {
      this.formDynamic.attrsName = ''
      this.formDynamic.attrsVal = ''
    },
    // 删除规格
    handleRemoveAttr(index) {
      this.isAttr = true
      this.formValidate.attr.splice(index, 1)
      this.manyFormValidate.splice(index, 1)
    },
    // 删除属性
    handleClose(item, index) {
      item.splice(index, 1)
    },
    // 添加规则名称
    createAttrName() {
      this.isAttr = true
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        const data = {
          attrName: this.formDynamic.attrsName,
          attrValue: [
            this.formDynamic.attrsVal
          ]
        }
        this.formValidate.attr.push(data)
        var hash = {}
        this.formValidate.attr = this.formValidate.attr.reduce(function (item, next) {
          /* eslint-disable */
          hash[next.attrName] ? '' : hash[next.attrName] = true && item.push(next)
          return item
        }, [])
        this.clearAttr()
        this.isBtn = false
      } else {
        this.$Message.warning('请添加完整的规格！');
      }
    },
    // 添加属性
    createAttr(num, idx) {
      this.isAttr = true
      if (num) {
        this.formValidate.attr[idx].attrValue.push(num);
        var hash = {};
        this.formValidate.attr[idx].attrValue = this.formValidate.attr[idx].attrValue.reduce(function (item, next) {
          /* eslint-disable */
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
        this.formValidate.attr[idx].inputVisible = false
      } else {
        this.$message.warning('请添加属性');
      }
    },
    // 详情
    getInfo() {
      this.fullscreenLoading = true
      productDetailApi(this.$route.params.id).then(async res => {
        this.isAttr = false;
        let info = res
        this.formValidate = {
          image: info.image,
          sliderImages: JSON.parse(info.sliderImage),
          sliderImage: info.sliderImage,
          storeName: info.storeName,
          storeInfo: info.storeInfo,
          keyword: info.keyword,
          cateIds: info.cateId.split(','), // 商品分类id
          cateId: info.cateId,// 商品分类id传值
          unitName: info.unitName,
          sort: info.sort,
          isShow: info.isShow,
          isBenefit: info.isBenefit,
          isNew: info.isNew,
          isGood: info.isGood,
          isHot: info.isHot,
          isBest: info.isBest,
          tempId: info.tempId,
          // attrValue: info.attrValue,
          attr: info.attr,
          selectRule: info.selectRule,
          isSub: info.isSub,
          content: info.content,
          specType: info.specType,
          id: info.id,
          giveIntegral: info.giveIntegral,
          ficti: info.ficti,
          coupons: info.coupons,
          activity: info.activityStr ? info.activityStr.split(',') : ['默认', '秒杀', '砍价', '拼团']
        }
        if (info.isHot) this.checkboxGroup.push('isHot')
        if (info.isGood) this.checkboxGroup.push('isGood')
        if (info.isBenefit) this.checkboxGroup.push('isBenefit')
        if (info.isBest) this.checkboxGroup.push('isBest')
        if (info.isNew) this.checkboxGroup.push('isNew')
        this.productGetRule()
        if (info.specType) {
          this.formValidate.attr = info.attr.map(item => {
            return {
              attrName: item.attrName,
              attrValue: item.attrValues.split(','),
              // inputVisible: false
            }
          })
          this.ManyAttrValue = info.attrValues;
          this.ManyAttrValue.forEach((val) => {
            this.attrInfo[Object.values(val.attrValue).sort().join('/')] = val
          })

          const tmp = {}
          const tmpTab = {}
          this.formValidate.attr.forEach((o, i) => {
            tmp['value' + i] = {title: o.attrName}
            tmpTab['value' + i] = ''
          })
          this.manyTabTit = tmp
          this.manyTabDate = tmpTab
          this.formThead = Object.assign({}, this.formThead, tmp)
        } else {
          this.OneattrValue = info.attrValue
          this.formValidate.attr = []
        }
        this.fullscreenLoading = false
      }).catch(res => {
        this.fullscreenLoading = false
        this.$message.error(res.message);
      })
    },
    handleRemove(i) {
      this.formValidate.sliderImages.splice(i, 1)
    },
    // 点击商品图
    modalPicTap(tit, num, i) {
      const _this = this
      this.$modalUpload(function (img) {
        if (tit === '1' && !num) {
          _this.formValidate.image = img[0].sattDir
          _this.OneattrValue[0].image = img[0].sattDir
        }
        if (tit === '2' && !num) {
          if (img.length > 10) return this.$message.warning("最多选择10张图片！");
          if (img.length + _this.formValidate.sliderImages.length > 10) return this.$message.warning("最多选择10张图片！");
          img.map((item) => {
            _this.formValidate.sliderImages.push(item.sattDir)
          });
        }
        if (tit === '1' && num === 'dan') {
          _this.OneattrValue[0].image = img[0].sattDir
        }
        if (tit === '1' && num === 'duo') {
          _this.ManyAttrValue[i].image = img[0].sattDir
        }
        if (tit === '1' && num === 'pi') {
          _this.oneFormBatch[0].image = img[0].sattDir
        }
      }, tit, 'content')
    },

    // 提交
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true
          productRegiserApi(this.formValidate).then(async res => {
            this.$message.success('上链编辑成功');
            setTimeout(() => {
              this.$router.push({path: '/store/index'});
            }, 500);
            this.fullscreenLoading = false
          }).catch(res => {
            this.fullscreenLoading = false
          })
        } else {
          if (!this.formValidate.hash) {
            this.$message.warning("请填写完整商品信息！");
          }
        }
      })
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = 'move'
      if (item === this.dragging) {
        return
      }
      const newItems = [...this.formValidate.sliderImages]
      const src = newItems.indexOf(this.dragging)
      const dst = newItems.indexOf(item)
      newItems.splice(dst, 0, ...newItems.splice(src, 1))
      this.formValidate.sliderImages = newItems;
    },
    handleDragEnterFont(e, item) {
      e.dataTransfer.effectAllowed = 'move'
      if (item === this.dragging) {
        return
      }
      const newItems = [...this.formValidate.activity]
      const src = newItems.indexOf(this.dragging)
      const dst = newItems.indexOf(item)
      newItems.splice(dst, 0, ...newItems.splice(src, 1))
      this.formValidate.activity = newItems;
    }
  }
}
</script>
<style scoped lang="scss">
.color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
}

.color-list .color-item.blue {
  background-color: #1E9FFF;
}

.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-list .color-item.green {
  background-color: #009688;
}

.color-list .color-item.red {
  background-color: #ed4014;
}

.proCoupon {
  /deep/ .el-form-item__content {
    margin-top: 5px;
  }
}

.tabPic {
  width: 40px !important;
  height: 40px !important;

  img {
    width: 100%;
    height: 100%;
  }
}

.noLeft {
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
  }
}

.tabNumWidth {
  /deep/ .el-input-number--medium {
    width: 121px !important;
  }

  /deep/ .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }

  /deep/ .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }

  /deep/ .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }

  /deep/ thead {
    line-height: normal !important;
  }

  /deep/ .el-table .cell {
    line-height: normal !important;
  }
}

.selWidth {
  width: 100%;
}

.selWidthd {
  width: 300px;
}

.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}

.labeltop {
  /deep/ .el-form-item__label {
    float: none !important;
    display: inline-block !important;
    margin-left: 120px !important;
    width: auto !important;
  }
}
</style>
